package com.ellricky.baselib.ui.order

import android.view.View
import android.widget.AdapterView
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andr.common.ui.fragment.BaseFragment
import com.andr.common.ui.fragment.BaseToolBarFragment
import com.andr.common.ui.mvp.BasePresenter
import com.andr.common.util.ToastUtil
import com.andr.common.widget.refresh.RvRefreshListener
import com.ellricky.baselib.BaseConstant
import com.ellricky.baselib.R
import com.ellricky.baselib.adapter.CommonGridItemDecoration
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.dialog.picker.EPickerUtil
import com.ellricky.baselib.entity.BaseData
import com.ellricky.baselib.entity.IdNamePickerEntity
import com.ellricky.baselib.entity.StudentWorkInfo
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.ui.student.StudentDetailActivity
import com.ellricky.baselib.util.*
import kotlinx.android.synthetic.main.activity_student_works.*
import java.util.*
import kotlin.collections.ArrayList

class StudentWorksFragment : BaseFragment<Void, BasePresenter<Void>>(), RvRefreshListener,
    AdapterView.OnItemClickListener {

    private var paramMap: HashMap<String, String> = hashMapOf()
    private var dataSource: List<StudentWorkInfo> = arrayListOf()

    //日期 年月/年月日
    private var date: String =
        TimeUtils.date2String(Date(), TimeUtils.FORMAT_DIVER_MONTH)

    //查询用户id
    private var empEid = LocalCacheUtil.getUid()

    private var refresh = false
    private var ePickerUtil: EPickerUtil? = null
    private var jobLevel = ""

    private var mDateType = BaseConstant.MONTH

    private val levelList by lazy {
        val list = arrayListOf<IdNamePickerEntity>();
        list.add(IdNamePickerEntity("", "全部"))
        list.add(IdNamePickerEntity("0", "未上传"))
        list.add(IdNamePickerEntity("1", "优秀"))
        list.add(IdNamePickerEntity("2", "正常"))
        list.add(IdNamePickerEntity("3", "差"))
        list
    }

    private var teacherList: MutableList<IdNamePickerEntity>? = null

    private var schoolId: String = ""
        get() {
            return if (LocalCacheUtil.isPresidentRole()) {
                LocalCacheUtil.getSchoolId()
            } else {
                field
            }
        }

    private var isSelectAllSchool = false

    private val workAdapter by lazy {
        StudentWorkAdapter()
    }

    override fun getContentLayout(): Int {
        return R.layout.activity_student_works
    }

    companion object {
        fun newInstance(): StudentWorksFragment {
            return StudentWorksFragment()
        }
    }

    override fun initUIView(view: View) {
        tv_title.text = "作品管理"

        rvView.init(this)
        ePickerUtil = EPickerUtil(requireActivity())
        with(rvView) {
            setLayoutManager(GridLayoutManager(context, 2))
            addItemDecoration(CommonGridItemDecoration(context, 2, 10))
        }

        initListener()
    }

    private fun initListener() {
        //选择人员
        tv_teacher?.setOnClickListener {
            if (!teacherList.isNullOrEmpty()) {
                ePickerUtil?.showCustomPicker(teacherList, null) { _, entry ->
                    if (entry.name == "全部校区") {
                        isSelectAllSchool = true
                        tv_teacher.text = entry.name
                        empEid = LocalCacheUtil.getUid()

                        //如果选择了全部校区 对应的作品等级只选择为优秀 其他不能选择
                        val idNamePickerEntity = levelList.find { it.name == "优秀" }
                        jobLevel = idNamePickerEntity?.id ?: ""
                        tv_level_status.text = idNamePickerEntity?.name ?: ""
                    } else {
                        isSelectAllSchool = false
                        tv_teacher.text = entry.name
                        empEid = entry.id
                    }

                    loadDataOnInit()
                }
            } else {
                ToastUtil.show(requireContext(), "请稍后重试")
            }
        }


        //选择时间
        tv_date?.setOnClickListener {
            //yyyy-mm
            if (mDateType == BaseConstant.MONTH) {
                ePickerUtil?.showMonthMnPicker("") { content,
                                                     _,
                                                     _ ->
                    tv_date.text = TimeUtils.convertFormat(
                        content,
                        TimeUtils.FORMAT_DIVER_MONTH,
                        TimeUtils.FORMAT_MONTH
                    )
                    date = content ?: ""
                    loadDataOnInit()
                }
            } else {
                //yyyy-mm-dd
                ePickerUtil?.showDayMnPicker("") { content,
                                                   _,
                                                   _ ->
                    tv_date.text = TimeUtils.convertFormat(
                        content,
                        TimeUtils.FORMAT_DIVER_MONTH_DAY,
                        TimeUtils.FORMAT_MONTH_DAY
                    )
                    date = content ?: ""
                    loadDataOnInit()
                }
            }
        }

        tv_level_status?.setOnClickListener {
            val levelName = tv_teacher.text.toString()
            if (levelName == "全部校区") return@setOnClickListener
            ePickerUtil?.showCustomPicker(levelList, null) { _,
                                                             content ->

                jobLevel = content.id
                tv_level_status.text = content.name
                loadDataOnInit()
            }
        }

        switchmultibutton.setOnSwitchListener { position, _ ->
            if (position == 0) {
                //yyyy-mm-dd
                date = TimeUtils.date2String(Date(), TimeUtils.FORMAT_DIVER_MONTH_DAY)
                mDateType = BaseConstant.MONTH_AND_DAY
                tv_date.text = TimeUtils.date2String(Date(), TimeUtils.FORMAT_MONTH_DAY)
            } else {
                //yyyy-mm
                date = TimeUtils.date2String(Date(), TimeUtils.FORMAT_DIVER_MONTH)
                mDateType = BaseConstant.MONTH
                tv_date.text = TimeUtils.date2String(Date(), TimeUtils.FORMAT_MONTH)
            }
            loadDataOnInit()
        }

        tv_date.text = TimeUtils.date2String(Date(), TimeUtils.FORMAT_MONTH)

        loadDataOnInit()
        loadTeacherList()
    }

    private fun initParamMap() {
        paramMap["action"] = "memberjobList"
        paramMap["eid"] = LocalCacheUtil.getUid()
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        paramMap["page"] = rvView.getCurPage().toString()
        paramMap["page_size"] = "40"
        paramMap["job_level"] = jobLevel
        paramMap["emp_eid"] = empEid
        if (isSelectAllSchool) {
            paramMap["school_id"] = schoolId
        }

        if (paramMap.containsKey("day")) {
            paramMap.remove("day")
        }
        if (paramMap.containsKey("month")) {
            paramMap.remove("month")
        }
        if (mDateType == BaseConstant.MONTH_AND_DAY) {
            paramMap["day"] = date
        } else {
            paramMap["month"] = date
        }
    }

    private fun loadTeacherList() {
        val url = EAppUtil.getApiHost()
        val paramMap = hashMapOf<String, String>()
        paramMap["action"] = "schoolTeacherAndGzaList"
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        HttpUtils.getInstance()
            .postFrom(
                url,
                paramMap,
                object : NewEListCallback<IdNamePickerEntity>(requireActivity()) {
                    override fun onSuccess(data: MutableList<IdNamePickerEntity>, msg: String?) {
                        if (teacherList.isNullOrEmpty()) {
                            if (LocalCacheUtil.isPresidentRole()) {
                                teacherList = data
                                teacherList?.add(
                                    0,
                                    IdNamePickerEntity(LocalCacheUtil.getUid(), "全部")
                                )
                            } else {
                                teacherList =
                                    data.filter { it.id == LocalCacheUtil.getUid() }.toMutableList()
                                teacherList?.add(IdNamePickerEntity("", "全部校区"))
                            }
                        }
                    }
                })
    }

    override fun setAdapter(rv: RecyclerView) {
        rv.adapter = workAdapter
        workAdapter.setOnItemClickListener(this)
    }

    private fun loadDataOnInit() {
        rvView.loadContent(true)
    }

    override fun loadData(refresh: Boolean) {
        this.refresh = refresh
        val url = EAppUtil.getApiHost()
        initParamMap()
        val callback: NewEBaseCallback = getResponseCallback2()
        HttpUtils.getInstance().postFrom(url, paramMap, callback)
    }

    private fun getResponseCallback2(): NewEBaseCallback {
        return object : NewEListCallBack2<StudentWorkInfo>(requireActivity()) {
            override fun onSuccess(
                data: MutableList<StudentWorkInfo>,
                baseData: BaseData<StudentWorkInfo>,
                msg: String?
            ) {
                dataSource = data
                rvView.onLoadFinish(data, refresh)
                tv_order_number.text = "作品数量：${baseData.allcount}张"
            }
        }
    }

    override fun updateAdapterData(refresh: Boolean) {
        if (refresh) workAdapter.refresh(dataSource)
        else workAdapter.loadMore(dataSource)
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        jump<StudentWorksDetailActivity> {
            val bean = workAdapter.get(position)
            putExtra("id", bean.job_id)
        }
    }
}